<template>
  <div class="invoice-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>发票管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleApply">申请开票</el-button>
            <el-button type="success" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="发票类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择发票类型" clearable>
            <el-option
              v-for="item in invoiceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择开票状态" clearable>
            <el-option
              v-for="item in invoiceStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 发票统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>待开票</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.pendingCount }}</div>
              <div class="label">张</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>已开票</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.issuedCount }}</div>
              <div class="label">张</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>已作废</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.voidCount }}</div>
              <div class="label">张</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>开票金额</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.totalAmount }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 发票列表 -->
      <el-table
        v-loading="loading"
        :data="invoiceList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="invoiceNo" label="发票编号" width="180" />
        <el-table-column prop="type" label="发票类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getInvoiceTypeTag(row.type)">
              {{ getInvoiceTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="开票金额" width="120">
          <template #default="{ row }">
            ¥ {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="发票抬头" width="180" />
        <el-table-column prop="taxNo" label="税号" width="180" />
        <el-table-column prop="status" label="开票状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getInvoiceStatusTag(row.status)">
              {{ getInvoiceStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column prop="issueTime" label="开票时间" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 0"
              link
              type="success"
              @click="handleIssue(row)"
            >
              开票
            </el-button>
            <el-button
              v-if="row.status === 1"
              link
              type="danger"
              @click="handleVoid(row)"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 申请开票对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="申请开票"
      width="600px"
    >
      <el-form
        ref="applyFormRef"
        :model="applyForm"
        :rules="applyRules"
        label-width="100px"
      >
        <el-form-item label="发票类型" prop="type">
          <el-select v-model="applyForm.type" placeholder="请选择发票类型">
            <el-option
              v-for="item in invoiceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票金额" prop="amount">
          <el-input-number
            v-model="applyForm.amount"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="发票抬头" prop="title">
          <el-input v-model="applyForm.title" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="税号" prop="taxNo">
          <el-input v-model="applyForm.taxNo" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="applyForm.email" placeholder="请输入接收发票的邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="applyForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="applyForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApply">提交申请</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发票详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="发票详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="发票编号">{{ detail.invoiceNo }}</el-descriptions-item>
        <el-descriptions-item label="发票类型">
          <el-tag :type="getInvoiceTypeTag(detail.type)">
            {{ getInvoiceTypeLabel(detail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开票金额">
          ¥ {{ detail.amount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="发票抬头">{{ detail.title }}</el-descriptions-item>
        <el-descriptions-item label="税号">{{ detail.taxNo }}</el-descriptions-item>
        <el-descriptions-item label="开票状态">
          <el-tag :type="getInvoiceStatusTag(detail.status)">
            {{ getInvoiceStatusLabel(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detail.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="开票时间">{{ detail.issueTime }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ detail.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detail.phone }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 开票对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="开具发票"
      width="500px"
    >
      <el-form
        ref="issueFormRef"
        :model="issueForm"
        :rules="issueRules"
        label-width="100px"
      >
        <el-form-item label="发票编号">
          <span>{{ issueForm.invoiceNo }}</span>
        </el-form-item>
        <el-form-item label="发票类型">
          <el-tag :type="getInvoiceTypeTag(issueForm.type)">
            {{ getInvoiceTypeLabel(issueForm.type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="开票金额">
          <span>¥ {{ issueForm.amount?.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="发票抬头">{{ issueForm.title }}</el-form-item>
        <el-form-item label="税号">{{ issueForm.taxNo }}</el-form-item>
        <el-form-item label="开票日期" prop="issueDate">
          <el-date-picker
            v-model="issueForm.issueDate"
            type="date"
            placeholder="选择开票日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="issueForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIssue">确认开票</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 作废对话框 -->
    <el-dialog
      v-model="voidDialogVisible"
      title="作废发票"
      width="500px"
    >
      <el-form
        ref="voidFormRef"
        :model="voidForm"
        :rules="voidRules"
        label-width="100px"
      >
        <el-form-item label="发票编号">
          <span>{{ voidForm.invoiceNo }}</span>
        </el-form-item>
        <el-form-item label="发票类型">
          <el-tag :type="getInvoiceTypeTag(voidForm.type)">
            {{ getInvoiceTypeLabel(voidForm.type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="开票金额">
          <span>¥ {{ voidForm.amount?.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="发票抬头">{{ voidForm.title }}</el-form-item>
        <el-form-item label="税号">{{ voidForm.taxNo }}</el-form-item>
        <el-form-item label="作废原因" prop="reason">
          <el-input
            v-model="voidForm.reason"
            type="textarea"
            placeholder="请输入作废原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="voidDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitVoid">确认作废</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getInvoiceList, exportInvoiceList, getInvoiceStatistics, applyInvoice, updateInvoiceStatus } from '@/api/finance'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  timeRange: []
})

// 发票类型选项
const invoiceTypes = [
  { label: '增值税普通发票', value: 'NORMAL' },
  { label: '增值税专用发票', value: 'SPECIAL' },
  { label: '电子发票', value: 'ELECTRONIC' }
]

// 发票状态选项
const invoiceStatus = [
  { label: '待开票', value: 0 },
  { label: '已开票', value: 1 },
  { label: '已作废', value: 2 }
]

// 统计数据
const statistics = ref({
  pendingCount: 0,
  issuedCount: 0,
  voidCount: 0,
  totalAmount: 0
})

// 表格数据
const loading = ref(false)
const invoiceList = ref([])
const total = ref(0)

// 申请开票对话框
const applyDialogVisible = ref(false)
const applyFormRef = ref(null)
const applyForm = ref({
  type: '',
  amount: 0,
  title: '',
  taxNo: '',
  email: '',
  phone: '',
  remark: ''
})

// 申请开票表单验证规则
const applyRules = {
  type: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入开票金额', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入发票抬头', trigger: 'blur' }
  ],
  taxNo: [
    { required: true, message: '请输入税号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 发票详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 开票对话框
const issueDialogVisible = ref(false)
const issueFormRef = ref(null)
const issueForm = ref({
  invoiceNo: '',
  type: '',
  amount: 0,
  title: '',
  taxNo: '',
  issueDate: '',
  remark: ''
})

// 开票表单验证规则
const issueRules = {
  issueDate: [
    { required: true, message: '请选择开票日期', trigger: 'change' }
  ]
}

// 作废对话框
const voidDialogVisible = ref(false)
const voidFormRef = ref(null)
const voidForm = ref({
  invoiceNo: '',
  type: '',
  amount: 0,
  title: '',
  taxNo: '',
  reason: ''
})

// 作废表单验证规则
const voidRules = {
  reason: [
    { required: true, message: '请输入作废原因', trigger: 'blur' }
  ]
}

// 获取发票类型标签
const getInvoiceTypeTag = (type) => {
  const map = {
    NORMAL: 'info',
    SPECIAL: 'success',
    ELECTRONIC: 'warning'
  }
  return map[type] || 'info'
}

// 获取发票类型标签文本
const getInvoiceTypeLabel = (type) => {
  const item = invoiceTypes.find(item => item.value === type)
  return item ? item.label : type
}

// 获取发票状态标签
const getInvoiceStatusTag = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || 'info'
}

// 获取发票状态标签文本
const getInvoiceStatusLabel = (status) => {
  const item = invoiceStatus.find(item => item.value === status)
  return item ? item.label : status
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getInvoiceList(queryParams.value)
    invoiceList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取发票列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getInvoiceStatistics(queryParams.value)
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStatistics()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    status: undefined,
    timeRange: []
  }
  handleQuery()
}

// 导出按钮点击
const handleExport = async () => {
  try {
    const res = await exportInvoiceList(queryParams.value)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '发票记录.xlsx'
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 申请开票按钮点击
const handleApply = () => {
  applyForm.value = {
    type: '',
    amount: 0,
    title: '',
    taxNo: '',
    email: '',
    phone: '',
    remark: ''
  }
  applyDialogVisible.value = true
}

// 提交申请
const submitApply = async () => {
  if (!applyFormRef.value) return
  
  await applyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await applyInvoice(applyForm.value)
        ElMessage.success('申请成功')
        applyDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('申请失败:', error)
        ElMessage.error('申请失败')
      }
    }
  })
}

// 查看详情
const handleDetail = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 开票按钮点击
const handleIssue = (row) => {
  issueForm.value = {
    invoiceNo: row.invoiceNo,
    type: row.type,
    amount: row.amount,
    title: row.title,
    taxNo: row.taxNo,
    issueDate: '',
    remark: ''
  }
  issueDialogVisible.value = true
}

// 提交开票
const submitIssue = async () => {
  if (!issueFormRef.value) return
  
  await issueFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateInvoiceStatus(issueForm.value.invoiceNo, {
          status: 1,
          issueDate: issueForm.value.issueDate,
          remark: issueForm.value.remark
        })
        ElMessage.success('开票成功')
        issueDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('开票失败:', error)
        ElMessage.error('开票失败')
      }
    }
  })
}

// 作废按钮点击
const handleVoid = (row) => {
  voidForm.value = {
    invoiceNo: row.invoiceNo,
    type: row.type,
    amount: row.amount,
    title: row.title,
    taxNo: row.taxNo,
    reason: ''
  }
  voidDialogVisible.value = true
}

// 提交作废
const submitVoid = async () => {
  if (!voidFormRef.value) return
  
  await voidFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await ElMessageBox.confirm('确认作废该发票吗？', '提示', {
          type: 'warning'
        })
        
        await updateInvoiceStatus(voidForm.value.invoiceNo, {
          status: 2,
          reason: voidForm.value.reason
        })
        ElMessage.success('作废成功')
        voidDialogVisible.value = false
        handleQuery()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('作废失败:', error)
          ElMessage.error('作废失败')
        }
      }
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.invoice-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
      
      .label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style> 